# Maintainer: Sergej Pupykin <arch+pub@sergej.pp.ru>
# Previous Maintainer: Jean Lucas <jean@4ray.co>
# Contributor: Vladimir Tsanev <tsachev@gmail.com>
# Contributor: MoeRT09 <https://aur.archlinux.org/account/MoeRT09>
# Contributor: jlkon13 <internet@devpi.de>

pkgname=coturn
pkgver=4.6.2
pkgrel=1
pkgdesc='Open-source implementation of TURN and STUN server'
arch=(loong64 x86_64)
url=https://github.com/coturn/coturn
license=(BSD)
depends=(libevent postgresql-libs libmariadbclient hiredis sqlite)
backup=(etc/turnserver/turnserver.conf)
source=($pkgname-$pkgver.tar.gz::$url/archive/$pkgver.tar.gz
        turnserver.service
        turnserver.sysusers.d
        turnserver.tmpfiles.d)
sha256sums=('13f2a38b66cffb73d86b5ed24acba4e1371d738d758a6039e3a18f0c84c176ad'
            'd625a21c96c34adeb74650892e84ee9e0b5c6774ee30e386218ef84d986b39c6'
            '92e51ecd664ab53031baa0aeee615fa7c4e73f79c5a3ebc49ac8e0919e4d23fd'
            'd765d14ff3a6527498257e4dc9e76231742cd41d8fe658004e171b8937db6a75')

build() {
  cd coturn-$pkgver
  export CFLAGS="$CFLAGS -ffat-lto-objects"
  ./configure \
    --prefix=/usr \
    --manprefix=/usr/share \
    --examplesdir=/usr/share/turnserver/examples \
    --disable-rpath
  make
}

check() {
  cd coturn-$pkgver
  make check
}

package() {
  install -Dm 644 turnserver.service -t "$pkgdir"/usr/lib/systemd/system
  install -Dm 644 turnserver.sysusers.d "$pkgdir"/usr/lib/sysusers.d/turnserver.conf
  install -Dm 644 turnserver.tmpfiles.d "$pkgdir"/usr/lib/tmpfiles.d/turnserver.conf
  ln -s turnserver.service "$pkgdir"/usr/lib/systemd/system/coturn.service

  cd coturn-$pkgver

  make DESTDIR="$pkgdir" install
  install -Dm 644 LICENSE -t "$pkgdir"/usr/share/licenses/coturn

  cd "$pkgdir"

  # Create needed directories
  install -dm 700 "$pkgdir"/etc/turnserver

  # Use Arch-specific directories in config
  mv {usr/etc/turnserver.conf.default,etc/turnserver/turnserver.conf}
  sed \
    -e '/^#log-file=\/var\/tmp\/turn.log$/c log-file=\/var\/log\/turnserver\/turn.log' \
    -e '/^#pidfile="\/var\/run\/turnserver.pid"$/c pidfile=\/run\/turnserver\/turnserver.pid' \
    -i etc/turnserver/turnserver.conf
  rmdir usr/etc

  # Remove unneeded executable bits
  find {etc,usr/include,usr/lib,usr/share,var} -type f ! -name '*.sh' ! -name '*.pl' -exec chmod 644 {} +
}
